/**
 * 
 */
package com.cqan.controller.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cqan.controller.BaseController;
import com.cqan.entity.Attachment;
import com.cqan.exception.AppException;
import com.cqan.service.attachment.AttachmentService;
import com.cqan.utils.encode.EncodeUtils;

/**
 * @author wuhui
 * 
 *         下午01:21:21
 */
@Controller
@RequestMapping(value = "/attachment")
public class AttachmentController extends BaseController {
	private String savepath;
	private String temppath;
	private AttachmentService attachmentService;
	
	final String[] unAllowedSuffix = new String[] { ".exe", ".bat" };

	@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
	public ModelAndView uploadFile(
			@RequestParam("attachment") MultipartFile attachment,String temp,
			HttpServletRequest request) throws IOException {
		
		ModelAndView mav = new ModelAndView("file");
		if (attachment.isEmpty()) {
			throw new AppException("upload.file");
		}
		String orginalFilename = attachment.getOriginalFilename();
		int li = orginalFilename.lastIndexOf(".");
		String ext = "";
		if (li != -1) {
			ext = orginalFilename.substring(li, orginalFilename.length());
		}
		List<String> exts = Arrays.asList(unAllowedSuffix);
		if (exts.contains(ext)) {
			throw new AppException("upload.suffix");
		}
		String fileName = EncodeUtils.md5(attachment.getInputStream());
		Attachment att = attachmentService.findBy("md5", fileName);
		if (savepath == null || temppath == null) {
			getPath();
		}
		String path = request.getSession().getServletContext().getRealPath("/");
		String tempsavepath = new StringBuffer().append(temppath).append(createSavePath()).toString();
		File tempsaveFile = new File(path+tempsavepath);
		if (!tempsaveFile.exists()) {
			tempsaveFile.mkdirs();
		}
		File savefile = new File(path+tempsavepath+fileName+ext);
		if (!savefile.exists()) {
			FileCopyUtils.copy(attachment.getBytes(), savefile);
			mav.addObject("exist", true);
		}else {
			mav.addObject("exist", false);
		}
		mav.addObject("fileName", orginalFilename);
		mav.addObject("file", tempsavepath+fileName+ext);
		return mav;
	}

	@RequestMapping(value = "/download.htm", method = RequestMethod.GET)
	public ModelAndView downloadFile(String attid, HttpServletRequest request,
			HttpServletResponse response) {
		if(attid==null||!"".equals(StringUtils.trim(attid))){
			throw new AppException("common.param");
		}
		Attachment attachment = attachmentService.get(attid);
		response.setCharacterEncoding("utf-8");  
        response.setContentType("multipart/form-data");  
        
        response.setHeader("Content-Disposition", "attachment;fileName="+attachment.getFileName());  
        try {  
        	String path = request.getSession().getServletContext().getRealPath("/");
            File file=new File(path+attachment.getUrl());  
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
            os.close();
        } catch (FileNotFoundException e) {  
        	throw new AppException("common.notfoundfile");  
        } catch (IOException e) {  
        	throw new AppException("common.io");
        }  
		return null;
	}

	public void getPath() throws IOException {

		Properties prop = new Properties();
		InputStream is = this.getClass().getResourceAsStream(
				"/application.properties");
		if (is != null) {
			prop.load(is);
			savepath = prop.getProperty("resource.savepath");
			temppath = prop.getProperty("resource.temppath");
		}
		is.close();
	}

	public String createSavePath() {
		Calendar calendar = Calendar.getInstance();
		String path = new StringBuffer("/").append(
				String.valueOf(calendar.get(Calendar.YEAR))).append("/")
				.append(calendar.get(Calendar.MONTH) + 1).append("/").append(
						calendar.get(Calendar.DATE)).append("/").toString();
		return path;
	}

	@Autowired
	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}
	
	

}
